package com.haredot.service.impl;

import com.haredot.constraint.RedisConst;
import com.haredot.entity.Advert;
import com.haredot.entity.Swiper;
import com.haredot.holder.TokenContextHolder;
import com.haredot.mapper.ResourceMapper;
import com.haredot.mapper.SwiperMapper;
import com.haredot.service.IndexService;
import com.haredot.vo.AttentionUserVo;
import com.haredot.vo.R;
import com.haredot.vo.ResourceViewVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private RedisTemplate<String, ResourceViewVo>  redisTemplate ;

    @Value("${spring.application.name}")
    private String applicationName ;

    @Resource
    private ResourceMapper resourceMapper ;

    @Resource
    private SwiperMapper swiperMapper ;

    @Override
    public R<?> queryIndexData() {
        Map<String, Object>  map = new HashMap<>();
        // 查询轮播图
        List<Swiper> allSwiper = swiperMapper.findAllSwiper(applicationName);
        map.put("swipers", allSwiper) ;

        // 随机查询一个广告位
        Advert advert = swiperMapper.findAdvertByRank(applicationName);
        map.put("advert", advert) ;
        // 查询热门资源
        Set<ZSetOperations.TypedTuple<ResourceViewVo>> typedTuples = redisTemplate.opsForZSet()
                .reverseRangeWithScores(RedisConst.RESOURCE_VISIT_RANK_SET, 0, 11);

        map.put("hotResources", typedTuples) ;
        // 查询精选资源
        List<ResourceViewVo> coreResources = resourceMapper.queryCoreResourcesTop12() ;

        // 获取对应资源的访问量
        List<Map<String, Object>> list = coreResources.stream().map(resourceViewVo -> {
            Double score = redisTemplate.opsForZSet().score(RedisConst.RESOURCE_VISIT_RANK_SET, resourceViewVo);
            return Map.of("score", score == null ? 0 : score, "value", resourceViewVo);
        }).toList();

        map.put("coreResources", list) ;

        // 获取当前登录的用户 （可能为空，匿名）
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        Long userId = null ;
        if (authentication != null && !"anonymousUser".equals(authentication.getName())) {
             userId = TokenContextHolder.getCurrentUserId();
        }
        // 查询作者推荐, 查询上传资源数量最多的前9个用户
        List<AttentionUserVo> attentionUserVoList = resourceMapper.findAttentionTop9(userId);
        map.put("attentions", attentionUserVoList) ;

        return R.ok().data(map) ;
    }

    @Override
    public R<?> queryAdvert() {
        Advert advert = swiperMapper.findAdvertByRank(applicationName);
        return R.ok().data(advert) ;
    }
}
